<?php
namespace app\admin\model;
use think\Model;
use think\Db;
use think\facade\Config;
/**
 * 通道模型
 * @package app\admin\model
 */
class Platfrom extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'bus_platfrom';
    protected $observerClass = 'app\admin\event\DeleteCache';
    public function searchMarkingAttr($query, $value, $data)
    {
        if(isMmsOrSms()){
            $query->where('marking',1);
        }
        
    }
    /**
     * 获取通道信息集
     * @Author   lf
     * @DateTime 2018-07-03T16:08:38+0800
     * @param    [type]                   $where [查询条件：数组]
     * @return   [type]                          [description]
     */
    public function getPlatfromAll($where=[])
    {
    	$data = [];
    	if(session('user_type')=='admin')
    	{
    		$data = $this::withSearch(['marking'])->alias('bp')
            ->field('bp.id,bp.plat_id,bp.mainnum,bp.maxsms,bp.send_priority,bp.plat_type,bp.plat_name_show,bp.platfrom,bp.create_time,sms_code.code,bpc.onoff,bpc.cmpp_status,bpcc.desc,bpcc.ip')
            ->where($where)
            ->join('sms_code', 'sms_code.id = bp.save_code','LEFT')
            ->join('bus_plat_cmpp bpc', 'bpc.plat_id = bp.plat_id','LEFT')
            ->join('bus_cmpp_client_reg_center bpcc', 'bpcc.id = bpc.reg_id','LEFT')
            ->paginate(15);
    	}
    	return $data;
    }

    /**
     * [getPlatfromAlls 获取通道信息]
     * @author   .guo
     * @DataTime 2019-05-30
     * @param    [type]     $request [description]
     * @return   [type]              [description]
     */
    public function getPlatfromAlls($request)
    {
        $data = [];

        if(session('user_type')=='admin') {

            $data = $this::withSearch(['marking'])->alias('bp')
                ->field('bp.id,bp.plat_id,bp.mainnum,bp.sms_price,bp.plat_name_show,bp.maxsms,bp.send_priority,bp.plat_type,bp.platfrom,bp.create_time,sms_code.code,bpc.onoff,bpc.cmpp_status,bpcc.desc,bpcc.ip,bp.use_temp_id,bp.plat_black_off')
                ->join('sms_code', 'sms_code.id = bp.save_code','LEFT')
                ->join('bus_plat_cmpp bpc', 'bpc.plat_id = bp.plat_id','LEFT')
                ->join('bus_cmpp_client_reg_center bpcc', 'bpcc.id = bpc.reg_id','LEFT');

            if($request['plat_id'])
            {
                $data = $data->where('bp.plat_id',$request['plat_id']);
            }

            $data = $data->paginate($request['limit'], false, $request)
                ->each(function($item, $key) {
                    switch ($item->plat_type) {

                        case 'CMPP':
                            if ($item->onoff == 1) {

                                $item->plat_type_ = '<span class="layui-badge layui-bg-green onoff-1">开启</span>';
                            } else {

                                $item->plat_type_ = '<span class="layui-badge onoff-0">禁用</span>';
                            }

                            if ($item->cmpp_status == 1) {

                                $item->cmpp_status_ = '<span class="layui-badge layui-bg-green cmpp_status-1">通讯中</span>';
                            } else {

                                $item->cmpp_status_ = '<span class="layui-badge cmpp_status-1">未连接</span>';
                            }


                            $item->cmpp_service = $item->desc ?: '';

                            break;

                        default:

                            $item->plat_type_ = '';
                            $item->cmpp_service = '';
                            break;
                    }
                    switch ($item->use_temp_id) {
                        case '0':
                            $item->use_temp_id = '<span class="layui-badge layui-bg-green onoff-1">'.$item->plat_type.'</span>'.'&nbsp;<span class="layui-badge layui-bg-green onoff-1">不用模板</span>';;
                            break;
                        case '1':
                            $item->use_temp_id = '<span class="layui-badge layui-bg-green onoff-1">'.$item->plat_type.'</span>'.'&nbsp;<span class="layui-badge layui-bg-blue onoff-1">视频模板</span>';
                            break;
                        case '2':
                            $item->use_temp_id = '<span class="layui-badge layui-bg-green onoff-1">'.$item->plat_type.'</span>'.'&nbsp;<span class="layui-badge layui-bg-blue onoff-1">SIM模板</span>';
                            break;
                        case '3':
                            $item->use_temp_id = '<span class="layui-badge layui-bg-green onoff-1">'.$item->plat_type.'</span>'.'&nbsp;<span class="layui-badge layui-bg-blue onoff-1">普通模板</span>';
                            break;
                        case '4':
                            $item->use_temp_id = '<span class="layui-badge layui-bg-green onoff-1">'.$item->plat_type.'</span>'.'&nbsp;<span class="layui-badge layui-bg-blue onoff-1">视频模板内容</span>';
                            break;

                        default:
                            $item->use_temp_id = '<span class="layui-badge layui-bg-green onoff-1">'.$item->plat_type.'</span>'.'&nbsp;<span class="layui-badge onoff-0">未知类型</span>';
                            break;
                    }

                    switch ($item->plat_black_off) {

                        case '0':
                            $item->plat_black_off = '<span class="layui-badge onoff-0">禁用</span>';
                            break;
                        case '1':
                            $item->plat_black_off = '<span class="layui-badge layui-bg-green onoff-1">开启</span>';
                            break;

                        default:
                            break;
                    }
                    // switch ($item->plat_group) {
                    //     case 'SINGLE':
                    //         $item->plat_group = '单类型';
                    //         break;
                    //     case 'GROUP':
                    //         $item->plat_group = '组合型';
                    //         break;

                    //     default:
                    //         # code...
                    //         break;
                    // }

            });
        }

        $redis = $this->getRides();

        foreach ($data as $key => $value) {

            $speed = $redis->get("HTTP_SL_".$value['plat_id']);

            $data[$key]['speed'] = $speed === false ? "未设置" : $speed."每秒";
        }

        return $data;
    }

    /**
     * 添加通道
     * @Author   lf
     * @DateTime 2018-07-03T16:42:03+0800
     * @param    [type]                   $platname [通道名]
     */
    public function addPlatfromOne($add)
    {
        $speed = $add['speed'];
        unset($add['speed']);
        $maxid = $this->field('max(plat_id) as plat_id')->find();

        try {
            $add['plat_id']     = $maxid['plat_id']+1;
            $add['create_time'] = date('Y-m_d H:i:s');
            $add['create_user'] = session('username');
            $add['update_time'] = date('Y-m_d H:i:s');
            $add['update_user'] = session('username');
            $this->isUpdate(false)->save($add);

            //速率
            $redis = $this->getRides();
            if($speed){
                $redis->set("HTTP_SL_".$add['plat_id'] , '"' . $speed . '"');
                trace('速率修改:'.$speed,'info');
            }else{
                $redis->del("HTTP_SL_".$add['plat_id']);
            }

            trace('用户'.session('username').'添加通道:'.json_encode($add,JSON_UNESCAPED_UNICODE),'info');
            echo "success";
        } catch (Exception $e) {
            echo "添加失败，服务繁忙";
        }
    }

    /**
     * 编辑通道
     * @Author   lf
     * @DateTime 2018-07-03T17:01:08+0800
     * @param    [type]                   $plat_id  [通道id]
     * @param    [type]                   $platname [通道名]
     */
    public function setPlatfromOne($request)
    {
        try {
            $plat_id = $request['pid'];
            unset($request['pid']);
            $speed = $request['speed'];
            unset($request['speed']);

            $request['update_user'] = session('username');
            $request['update_time'] = date('Y-m_d H:i:s');

            $plat = $this->save($request,['plat_id'=>$plat_id]);

            //速率
            $redis = $this->getRides();
            if($speed){
                $redis->set("HTTP_SL_".$plat_id , '"' . $speed . '"');
                trace('速率修改:'.$speed,'info');
            }else{
                $redis->del("HTTP_SL_".$plat_id);
            }

            trace('用户'.session('username')."编辑通道:".json_encode($request,JSON_UNESCAPED_UNICODE),'info');
            echo "success";
        } catch (Exception $e) {
            echo "添加失败，服务繁忙";
        }
    }


    public function getRides()
    {
        $ZD_REDIS_CONFIG = Config::get('ZD_REDIS_CONFIG');
        return redisCurl($ZD_REDIS_CONFIG['IP'],$ZD_REDIS_CONFIG['PORT'],$ZD_REDIS_CONFIG['PASSWORD'],5);
    }
    //更新
    public static function upd($data)
    {
        try {
            self::update($data);
            deleteCache();
            return ['code' => '200', 'msg' => '修改成功'];
        } catch (\Exception $e) {
            return ['code' => '422', 'msg' => '修改失败'];
        }
    }
}
